package com.example.systemend.util;

import com.example.systemend.pojo.User;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

/**
 * @author 权哥
 * @version 1.0
 * @date 2022/6/10 11:01
 */
public class JwtUtil {

    private static long EXPIRE_TIME=1000*60*60*24*14;
    private static String TOKEN_SECRET="LiQuan";

    public static String createToken(User user){
        JwtBuilder jwtBuilder= Jwts.builder();
        String jwtToken;
        jwtToken = jwtBuilder
                //header头
                .setHeaderParam("typ","TWT")
                .setHeaderParam("alg","HS256")
                //payload载荷
                .claim("username",user.getUsername())
                .claim("password",user.getPassword())
                .setSubject("test_li")
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_TIME))
                .setId(UUID.randomUUID().toString())
                //signature  签名
                .signWith(SignatureAlgorithm.HS256,TOKEN_SECRET)
                .compact();

        return jwtToken;
    }

    //校验token的合法性
    public static boolean checkToken(String token){

        if(token==null){
            System.out.println("不存在token！");
            return false;
        }
        try {
            //如果能正常解析
            Jws<Claims> claimsJws= Jwts.parser().setSigningKey(TOKEN_SECRET)
                    .parseClaimsJws(token);
            Claims claims=claimsJws.getBody();
            System.out.println("token合法,认证通过！");
            System.out.println("过期时间：" + claims.getExpiration());
        }catch (Exception e){

            System.out.println("token不合法！");
            return false;
        }

        return true;

    }

    public static void main(String[] args) {
        if(checkToken("eyJ0eXAiOiJUV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IuadjuadgyIsInBhc3N3b3JkIjoiTFEyMDAxMDMxMSIsInN1YiI6InRlc3RfbGkiLCJleHAiOjE2NTQ5MzExMzksImp0aSI6IjJhMjU3MTYwLThmN2YtNGE4YS1iYWZjLWVlYmQ0OTNlZjdkZCJ9.GjWfFVdw21ntpx-4Byz_ruGjnUSCHqS7SFS5k_RVZTk"))
            System.out.println("合法");
    }
}
